import axios from 'axios'
import store from '@/store'

const API_URL = 'http://localhost:8080/library'

class BookService {
    getAllBooks() {
        return new Promise((resolve) => {
            // 模拟数据
            resolve([
                {id: 1, isbn: '9787111636664', title: 'Java核心技术 卷I', author: '凯·S·霍斯特曼', publisher: '机械工业出版社', publishDate: '2019-12-01', category: '编程', status: '在库'},
                {id: 2, isbn: '9787121377969', title: '深入理解计算机系统', author: '兰德尔·E·布莱恩特', publisher: '电子工业出版社', publishDate: '2021-05-01', category: '计算机科学', status: '借出'},
                {id: 3, isbn: '9787302510055', title: 'Python编程：从入门到实践', author: '埃里克·马瑟斯', publisher: '人民邮电出版社', publishDate: '2020-07-01', category: '编程', status: '在库'},
                {id: 4, isbn: '9787115516017', title: '算法图解', author: '巴尔加瓦', publisher: '人民邮电出版社', publishDate: '2019-03-01', category: '算法', status: '在库'},
                {id: 5, isbn: '9787111544937', title: 'Clean Code', author: 'Robert C. Martin', publisher: '人民邮电出版社', publishDate: '2016-09-01', category: '编程', status: '维护中'}
            ])
        })
    }

    addBook(book) {
        return axios.post(`${API_URL}/books?action=add`, book, {
            headers: this.getAuthHeader()
        })
    }

    updateBook(book) {
        return axios.post(`${API_URL}/books?action=update`, book, {
            headers: this.getAuthHeader()
        })
    }

    deleteBook(id) {
        return axios.delete(`${API_URL}/books?id=${id}`, {
            headers: this.getAuthHeader()
        })
    }

    getAuthHeader() {
        const token = store.state.auth.token
        if (token) {
            return { 'Authorization': 'Bearer ' + token }
        } else {
            return {}
        }
    }
}

export default new BookService()